package com.oywy.rbac.service;

import com.oywy.rbac.entity.Authority;
import com.oywy.rbac.entity.Role;
import com.oywy.rbac.repository.AuthorityRepository;
import com.oywy.rbac.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.Collection;
import java.util.List;

/**
 * 角色服务
 *
 * @author oywy
 * @date 2018/10/22
 */
@Service
public class RoleService {
    @Autowired
    private RoleRepository roleRepo;
    @Autowired
    private AuthorityRepository authorityRepo;

    public List<Role> list() {
        return roleRepo.findAll();
    }

    public Role get(String id) {
        return roleRepo.findById(id).orElseThrow(EntityNotFoundException::new);
    }

    public Role post(Role role) {
        return roleRepo.save(role);
    }

    public Role put(Role role) {
        return roleRepo.save(role);
    }

    public void del(String id) {
        roleRepo.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public int grantAuthorities(String id, List<String> authorityIds) {
        List<Authority> authorities = authorityRepo.findAllById(authorityIds);
        Role role = roleRepo.findById(id).orElseThrow(NullPointerException::new);
        role.setAuthorities(authorities);
        roleRepo.save(role);
        return authorities.size();
    }
}
